grammar Calculator;

// 参考 javascript 语法定义里的 DecimalLiteral
// https://github.com/antlr/grammars-v4/blob/master/javascript/javascript/JavaScriptLexer.g4
NUMBER:       DecimalIntegerLiteral '.' [0-9] [0-9_]* ExponentPart?
              |                 '.' [0-9] [0-9_]* ExponentPart?
              |                 DecimalIntegerLiteral ExponentPart?
              ;

fragment DecimalIntegerLiteral
    : '0'
    | [1-9] [0-9_]*
    ;
fragment ExponentPart
    : [eE] [+-]? [0-9_]+
    ;

VAR: [a-zA-Z][a-zA-Z0-9]*;  // 匹配变量
DIV: '/';
MUL: '*';
ADD: '+';
SUB: '-';
WS : [ \t\r\n]+ -> skip;

// 定义表达式
expr: expr op=('*'|'/') expr      # MulOrDiv
    | expr op=('+'|'-') expr      # AddOrSub
    | '(' expr ')'                # Parens
    | NUMBER                      # Number
    | VAR                         # Variable
    ;
prog: expr+ ;